package com.roncoo.eshop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.roncoo.eshop.dao.RedisDAO;
import com.roncoo.eshop.mapper.UserMapper;
import com.roncoo.eshop.model.User;
import com.roncoo.eshop.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户Service实现类
 *
 * @author Administrator
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisDAO redisDAO;

    @Override
    public User findUserInfo() {
        return userMapper.findUserInfo();
    }

    @Override
    public User getCachedUserInfo() {
        redisDAO.set("cached_user_lisi", "{\"name\": \"lisi\", \"age\":28}");

        String userJSON = redisDAO.get("cached_user_lisi");
        ObjectMapper mapper = new ObjectMapper();
        User user = new User();
        try {
            JsonNode jsonNode = mapper.readTree(userJSON);
            user.setName(jsonNode.get("name").asText());
            user.setAge(jsonNode.get("age").asInt());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }

//        JSONObject userJSONObject = JSONObject.parseObject(userJSON);
//
//
//        user.setName(userJSONObject.getString("name"));
//        user.setAge(userJSONObject.getInteger("age"));

        return user;
    }

}
